//
//  SyneminCoreDataManager.m
//  CoreDataTest
//
//  Created by 韩震明 on 15/11/20.
//  Copyright © 2015年 韩震明. All rights reserved.
//

#import "SyneminCoreDataManager.h"

#define Model_name @"Message"

#import "Message.h"




@implementation SyneminCoreDataManager

+ (SyneminCoreDataManager *)defaults
{
    static SyneminCoreDataManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[SyneminCoreDataManager alloc] init];
        
    });
    return manager;
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "Synemin.CoreDataTest" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:MODEL_NAME withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.sqlite", MODEL_NAME]];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
//    
//    NSDictionary *options = [NSDictionary dictionaryWithObject:@(YES) forKey:NSMigratePersistentStoresAutomaticallyOption];
    
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

#pragma mark - Add to Core Data SQLite
/**
 *  添加
 *
 *  @param from    发送者
 *  @param to      接收者
 *  @param message 发送的内容
 */
- (void)addFrom:(NSString *)from to:(NSString *)to message:(NSString *)message
{
    NSEntityDescription *entity = [NSEntityDescription entityForName:ENTITY_NAME inManagedObjectContext:self.managedObjectContext];
    
    // 在这里修改类以便于insert
    Message *mes = [[Message alloc] initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];
    
    mes.to = to;
    mes.from = from;
    mes.message = message;
    
    // 获取本地时间
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd-HH-mm-ss"];
    NSString *time = [dateFormatter stringFromDate:date];
    
    mes.time = time;
    
    [self saveContext];
    
}

#pragma mark - Select From Core Data SQLite
/**
 *  检索本地
 *
 *  @param selectPredicate 谓词
 *  @param arguments       检索条件
 *
 *  @return 检索结果(数组)
 */
- (NSArray *)selectFormatString:(NSString *)selectPredicate arguments:(NSString *)arguments
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:ENTITY_NAME inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    // 限制条件为空时搜索所有
    if (selectPredicate != nil && arguments != nil) {
        
        NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", selectPredicate, @"%@"], arguments];
        [fetchRequest setPredicate:predicate];
    }
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"time"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"不能处理：%@", [error localizedDescription]); 
    }
    return fetchedObjects;
}

#pragma mark - Update SQLite
/**
 *  修改coredata
 *
 *  @param selectPredicate 谓词
 *  @param arguments       检索条件
 */
- (void)updateFromSelectFormatString:(NSString *)selectPredicate arguments:(NSString *)arguments
{
    NSArray *arr = [NSArray array];
    arr = [self selectFormatString:selectPredicate arguments:arguments];
    
    // 在这修改类的接受 以便于update
    Message *mes = [[Message alloc] init];
    if ([@"to" isEqualToString:selectPredicate]) {
        mes.to = arguments;
    } else if ([@"from" isEqualToString:selectPredicate]) {
        mes.from = (NSString *)arguments;
    } else if ([@"message" isEqualToString:selectPredicate]) {
        mes.message = (NSString *)arguments;
    }
    
    [self saveContext];
}

- (void)deleteFromSelectFormatString:(NSString *)selectPredicate arguments:(NSString *)arguments
{
    NSArray *arr = [NSArray array];
    arr = [self selectFormatString:selectPredicate arguments:arguments];
    
    for (Message *contact in arr) {
        [self.managedObjectContext deleteObject:contact];
        
    }
    [self saveContext];
}

/**
 *  查询所有本地数据
 *
 *  @return 本地所有数据(数组)
 */
- (NSArray *)selectAll
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:ENTITY_NAME inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"不能处理：%@", [error localizedDescription]);
    }
    
    return fetchedObjects;
}





@end
